<template>
  <div style="padding:20px">
    <el-row :gutter="12">
      <el-col :span="12">
        <el-card class="chat-card" shadow="never">
          <h2>AI 对话 - 基于知识库的搜索式智能问答</h2>
          <el-select v-model="selectedKB" placeholder="请选择知识库" style="width: 100%; margin-bottom: 20px;">
            <el-option v-for="kb in knowledgeBases" :key="kb.id" :label="kb.name" :value="kb.id">
            </el-option>
          </el-select>
          <div class="chat-window" ref="chatWindow">
            <div v-for="(message, index) in messages" :key="index"
              :class="{ 'user-message': message.type === 'user', 'bot-message': message.type === 'bot' }"
              style="margin: 8px;">
              <p v-if="message.type === 'user'" style="line-height: 24px;padding:2px 8px;color:#000">
                <strong>{{ message.type === 'user' ? '我:' : '含光:' }}</strong>{{ message.content }}
              </p>
              <p v-else style="   line-height: 24px;padding:2px 8px;color:#000">
                <strong>{{ message.type === 'user' ? '我:' : '含光:' }}</strong>{{ message.content }}
              </p>
            </div>
          </div>
          <el-input v-model="userInput" type="textarea" :rows="2" placeholder="请输入你的问题..."
            @keyup.enter.native="sendMessage" style="margin-top: 12px;">
            <template #append>
              <el-button icon="el-icon-s-promotion" @click="sendMessage"></el-button>
            </template>
          </el-input>
          <el-button icon="el-icon-s-promotion" @click="sendMessage" style="width: 100%;margin-top: 12px;"
            type="primary">发送</el-button>
        </el-card>
      </el-col>
      <el-col :span="12">

        <el-card class="chat-card" shadow="never">
          <h2>AI 知识库检索结果</h2>

          <div v-if="knowledgeResults.length === 0" style="text-align: center;">
            <i class="el-icon-document-empty" style="font-size: 50px;"></i>
            <el-empty description="暂无知识片段"></el-empty>
          </div>
          <div v-else style="height: 545px;overflow: auto;-ms-overflow-style: none;border-radius: 8px;
scrollbar-width: none; /* Firefox */">
            <div v-for="k, index in knowledgeResults">
              <div style="background-color: #f3f4f5;padding:8px 12px;margin:4px;overflow-x: auto;white-space: nowrap;-ms-overflow-style: none; border-radius: 8px;
scrollbar-width: none; /* Firefox */">
                <span style="font-size: 18px;">{{ index + 1 }}.</span>
                <span>{{ k.content }}</span>
                <div
                  style="background-color: #fff;padding: 4px 8px;border-radius: 8px;margin: 4px;white-space: nowrap;">
                  <div><small><strong>{{ k.file_name }}</strong></small> | <small><strong>{{ k.download_url
                        }}</strong></small></div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      selectedKB: '',
      knowledgeBases: [],
      userInput: '',
      messages: [],
      knowledgeResults: []
    };
  },
  methods: {
    async fetchKnowledgeBases() {
      try {
        const response = await fetch(`${import.meta.env.VITE_API_URL}/knowledgeBases`, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          }
        });
        if (response.status === 401) {
          localStorage.removeItem('access_token');
          this.$router.push('/login');
          return;
        }
        let data = await response.json();
        data = data.data
        this.knowledgeBases = data;
      } catch (error) {
        console.error(error);
      }
    },
    async sendMessage() {
      if (!this.selectedKB) {
        ElMessage.warning('请选择一个知识库');
        return;
      }
      if (!this.userInput.trim()) {
        ElMessage.warning('请输入您的问题');
        return;
      }
      this.searchDoc()
      this.messages.push({ type: 'user', content: this.userInput });
      this.messages.push({ type: 'assistant', content: "" });

      try {
        const response = await fetch(`${import.meta.env.VITE_API_URL}/aiSearch/answer`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          },
          body: JSON.stringify({
            kdbListChecked: this.selectedKB,
            keywords: this.userInput
          })
        });

        if (response.status === 401) {
          localStorage.removeItem('access_token');
          this.$router.push('/login');
          return;
        }
        if (!response.ok) {
          throw new Error('Network response was not ok ' + response.statusText);
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let done = false;
        let botResponse = '';

        while (!done) {
          const { value, done: doneReading } = await reader.read();
          done = doneReading;
          const chunk = decoder.decode(value, { stream: !done });
          botResponse += chunk;
          // 更新消息数组并滚动到底部
          this.messages[this.messages.length - 1].content = botResponse;
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        }

        // this.messages.push({ type: 'bot', content: botResponse });
      } catch (error) {
        console.error(error);
        this.messages.push({ type: 'bot', content: '发生错误，请稍后再试。' });
      }

      this.userInput = '';
    },
    searchDoc() {
      if (!this.selectedKB) {
        ElMessage.warning('请选择一个知识库');
        return;
      }
      if (!this.userInput.trim()) {
        ElMessage.warning('请输入您的问题');
        return;
      }


      try {
        fetch(`${import.meta.env.VITE_API_URL}/aiSearch/searchDoc`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          },
          body: JSON.stringify({
            kdbListChecked: this.selectedKB,
            keywords: this.userInput
          })
        }).then((response) => {
          if (response.status === 401) {
            localStorage.removeItem('access_token');
            this.$router.push('/login');
            return;
          }
          if (!response.ok) {
            throw new Error('Network response was not ok ' + response.statusText);
          }
          return response.json();
        }).then((data) => {
          console.log("文档搜索结果：", data);
          this.knowledgeResults = data?.data?.kdbRSList[0]?.kdbRS || []
          // 在这里处理数据，例如更新 UI
        }).catch((error) => {
          console.error('There has been a problem with your fetch operation:', error);
        });
        // this.messages.push({ type: 'bot', content: data.answer });
        // this.scrollToBottom();
      } catch (error) {
        console.error(error);
        // this.messages.push({ type: 'bot', content: '发生错误，请稍后再试。' });
      }

      // this.userInput = '';
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const chatWindow = this.$refs.chatWindow;
        chatWindow.scrollTop = chatWindow.scrollHeight;
      });
    }
  },
  mounted() {
    this.fetchKnowledgeBases();
  }
};
</script>

<style scoped>
.chat-card {
  width: 100%;
  text-align: left;
}

.chat-window {
  height: 360px;
  overflow-y: scroll;
  border: 1px solid #ccc;
  padding: 0px;
  margin-bottom: 20px;
}

.user-message {
  text-align: right;
  margin-bottom: 10px;
}

.bot-message {
  text-align: left;
  margin-bottom: 10px;
}
</style>